<template>
  <div id="patrolTaskEdit">
    <GoBack content="订单信息维护" :backUrl="backUrl" />
    <div class="bodyContent">
      <!-- 三目运算判断 -->
      <vxe-toolbar perfect>
        <template #buttons>
          <el-form ref="taskFormRef" :model="taskForm" :rules="taskFormRule" label-width="140px" class="form-input-m" :inline-message="true">
            <el-row>
<!--              <el-col :span="6">
                <el-form-item prop="workGroup" label="工作组">
                  <el-select v-model="taskForm.workGroup" filterable placeholder="检测方式" style="width: 200px">
                    <el-option v-for="ctype in jygzzList" :key="ctype.code" :label="ctype.name" :value="ctype.code"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>-->
              <el-col :span="6">
                <el-form-item label="仓库" prop="tarStoreCode">
                  <VxePulldownSelectionWithNa
                    style="width: 100%"
                    :url="'/inv/storeManage/findStoreManageList'"
                    @confirmClick="SelectRowClick"
                    :tableColumn="[
                      { field: 'storeCode', title: '编码' },
                      { field: 'storeName', title: '名称' }
                    ]"
                    :aimKeys="[
                      { aimKey: 'tarStoreCode', rowKey: 'storeCode' },
                      { aimKey: 'tarStoreNa', rowKey: 'storeName' }
                    ]"
                    :displayTexts="['tarStoreNa']"
                    :displayTextObj="taskForm.tarStoreNa ? taskForm.tarStoreNa : ''"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="入库人" prop="storagePersonnel">
                  <VxePulldownSelection
                    v-enterNextInput
                    :url="'/api/user/getUserInfoList'"
                    @confirmClick="dropPullDownConfirm"
                    :tableColumn="[
                      { field: 'username', title: '编号', width: '60px' },
                      { field: 'realname', title: '姓名' }
                    ]"
                    :aimKeys="[{ aimKey: 'storagePersonnel', rowKey: 'username' }]"
                    :displayTexts="['realname']"
                    :displayTextObj="taskForm.storagePersonnel ? taskForm.storagePersonnel : ''"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="单据日期">
                  <el-date-picker style="width: 200px" v-model="taskForm.documentDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="purOrderNumber" label="采购单号">
                  <el-input v-model="taskForm.purOrderNumber" type="text" placeholder="请输入采购单号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="供应商" prop="supplierCode">
                  <VxePulldownSelectionWithNa
                    style="width: 100%"
                    :url="'/lis/inv/supplier/findInvSupplierList'"
                    @confirmClick="SelectRowClick"
                    :tableColumn="[
                      { field: 'supplierCode', title: '编码' },
                      { field: 'supplierName', title: '名称' }
                    ]"
                    :aimKeys="[
                      { aimKey: 'supplierCode', rowKey: 'supplierCode' },
                      { aimKey: 'supplierName', rowKey: 'supplierName' }
                    ]"
                    :displayTexts="['supplierName']"
                    :displayTextObj="taskForm.supplierName ? taskForm.supplierName : ''"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="invoiceNumber" label="采购发票号">
                  <el-input v-model="taskForm.invoiceNumber" type="text" placeholder="请输入采购发票号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="发票日期">
                  <el-date-picker style="width: 200px" v-model="taskForm.invoiceDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="流转方式" prop="transferType">
                  <el-select v-model="taskForm.transferType" filterable placeholder="流转方式" style="width: 200px">
                    <el-option v-for="ctype in lzList" :key="ctype.transferCode" :label="ctype.transferName" :value="ctype.transferCode"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </vxe-toolbar>

      <div class="contentDiv">
        <el-form :inline="true" :model="reagentForm">
          <el-form-item label="商品">
            <VxePulldownSelection @keyup="keyupEnter($event,0)" ref="form0"
                                  :url="'/lis/inv/invReagent/findInvReagentList'"
                                  @confirmClick="SelectRowClick1"
              :tableColumn="[
              { title: '商品代码', field: 'reaNo' },
              { title: '商品名称', field: 'reaNa' },
              { title: '规格', field: 'specModel' },
              { title: '有效期', field: 'expirDay' },
              { title: '单位', field: 'proUnit' },
              { title: '价格', field: 'costPrice' },
              { title: '商品条码', field: 'barcode' },
              { title: '供应商', field: 'vendorNo' },
              { title: '最小单位', field: 'miniUnit' },
              { title: '最高温度', field: 'maxTemp' },
              { title: '最低温度', field: 'minTemp' },
              { title: '储存条件', field: 'stockCondition' }
              ]"
              :aimKeys="[
                { formKey: 'reaNo', rowKey: 'reaNo' },
                { formKey: 'reaNa', rowKey: 'reaNa' },
                { formKey: 'specModel', rowKey: 'specModel' },
                { formKey: 'expirDay', rowKey: 'expirDay' },
                { formKey: 'proUnit', rowKey: 'proUnit' },
                { formKey: 'costPrice', rowKey: 'costPrice' },
                { formKey: 'barcode', rowKey: 'barcode' },
                { formKey: 'vendorNo', rowKey: 'vendorNo' },
                { formKey: 'miniUnit', rowKey: 'miniUnit' },
                { formKey: 'maxTemp', rowKey: 'maxTemp' },
                { formKey: 'minTemp', rowKey: 'minTemp' },
                { formKey: 'stockCondition', rowKey: 'stockCondition' }
              ]" :displayTexts="['reaNa']" :displayTextObj="reagentForm.reaNa" />
          </el-form-item>
          <el-form-item label="批号">
            <el-input @keyup="keyupEnter($event,1)" ref="form1" v-model="reagentForm.batchNum" type="text" placeholder="批号"></el-input>
          </el-form-item>
          <el-form-item label="有效期">
            <el-input @keyup="keyupEnter($event,2)" ref="form2" v-model="reagentForm.expirDay" type="text" placeholder="有效期"></el-input>
          </el-form-item>
          <el-form-item label="数量">
            <el-input @keyup="keyupEnter($event,3)" ref="form3" v-model="reagentForm.amount" type="text" placeholder="数量"></el-input>
          </el-form-item>
          <el-form-item label="价格">
            <el-input @keyup="keyupEnter($event,4)" ref="form4" v-model="reagentForm.costPrice" type="text" placeholder="价格"></el-input>
          </el-form-item>
        </el-form>
        <el-container>
          <el-aside width="100%">
            <el-divider content-position="left">
              商品信息
              <el-button size="small" type="success" class="add-btn" @click="showAddReagent">添加商品 </el-button>
            </el-divider>
            <el-dialog title="选择商品" v-model="checkReagentShow" :show-close="false" :modal-append-to-body="false" :close-on-click-modal="false" width="900px">
              <SelectReagent ref="sltReagentRef"></SelectReagent>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="confirmReagent">确定</el-button>
                <el-button @click="closeReagentDialog">取消</el-button>
              </div>
            </el-dialog>
            <div style="height: calc(100% - 150px)">
              <vxe-table class="mb10" border ref="reagentTableRef" :data="taskForm.reagentList" :row-config="{ isCurrent: true, isHover: true, useKey: true, keyField: 'eqId' }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow height="auto">
                <vxe-column type="seq" width="30" title=""></vxe-column>
                <vxe-column field="reaNo" title="商品代码" align="center"></vxe-column>
                <vxe-column field="reaNa" title="商品名称" align="center"></vxe-column>
                <vxe-column field="specModel" title="规格" align="center"></vxe-column>
                <vxe-column field="batchNum" title="批号" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
                  <template #default="{ row }">
                    <div>{{ row.batchNum }}</div>
                  </template>
                  <template #edit="{ row }">
                    <vxe-input v-model="row.batchNum" placeholder="批号" style="width: 100%"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="expirDay" title="有效期" align="center"></vxe-column>
                <vxe-column field="amount" title="数量" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
                  <template #default="{ row }">
                    <div>{{ row.amount }}</div>
                  </template>
                  <template #edit="{ row }">
                    <vxe-input v-model="row.amount" placeholder="数量" @change="getCosts(row)" style="width: 100%"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="proUnit" title="单位" align="center"></vxe-column>
                <vxe-column field="costPrice" title="价格" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
                  <template #default="{ row }">
                    <div>{{ row.costPrice }}</div>
                  </template>
                  <template #edit="{ row }">
                    <vxe-input v-model="row.costPrice" placeholder="价格" @change="getCosts(row)" style="width: 100%"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="costs" title="金额" align="center" ></vxe-column>

                <vxe-column field="produceDate" title="生产日期" width="100" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.produceDate" placeholder="日期选择" type="date"></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="expiryDate" title="有效期" width="120" :edit-render="{}">
                    <template #edit="{ row, rowIndex, column }">
                      <vxe-input v-model="row.expiryDate" placeholder="日期选择" type="date" transfer></vxe-input>
                    </template>
                  </vxe-column>
                <vxe-column field="applyNum" title="申请数量" ref="tableForm3" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
                  <template #default="{ row }">
                    <div>{{ row.applyNum }}</div>
                  </template>
                  <template #edit="{ row }">
                    <vxe-input v-model="row.applyNum" placeholder="申请数量" style="width: 100%"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="receiveNum" title="收货数量" ref="tableForm4" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
                  <template #default="{ row }">
                    <div>{{ row.receiveNum }}</div>
                  </template>
                  <template #edit="{ row }">
                    <vxe-input v-model="row.receiveNum" placeholder="收货数量" style="width: 100%"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="barcode" title="商品条码" align="center"></vxe-column>
                <vxe-column field="vendorNo" title="供应商" align="center"></vxe-column>
                <vxe-column field="miniUnit" title="最小单位" align="center"></vxe-column>
                <vxe-column field="maxTemp" title="最高温度" align="center"></vxe-column>
                <vxe-column field="minTemp" title="最低温度" align="center"></vxe-column>
                <vxe-column field="stockCondition" title="储存条件" align="center"></vxe-column>
              </vxe-table>
            </div>
            <div style="width: 100%; text-align: right; margin-top: 10px;">
              <el-button type="primary" v-loading="submiting" size="small" @click="saveForm('taskFormRef')">提交 </el-button>
              <el-button type="primary" v-loading="submiting" size="small" @click="goBack()">关闭 </el-button>
            </div>
          </el-aside>
        </el-container>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import GoBack from '@/components/GoBack.vue'; //返回组件
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
import SelectReagent from '@/components/SelectReagent.vue';
import { formatDateTime, IsEmpty } from '@/utils/common';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';

import { notifyMessage, notifyType } from '@/utils/common';

let { proxy }: any = getCurrentInstance();

let radio = ref(1);
let backUrl = ref('');
let userList: any = reactive([]);
let jygzzList: any = reactive([]);
let lzList: any = reactive([]);
let sltReagentRef = ref(null);
let reagentTableRef = ref(null);

let submiting = ref(false);
let checkReagentShow = ref(false);

let taskForm: any = reactive({
  id: '',
  planId: '',
  tarStoreCode: '',
  tarStoreNa: '',
  supplierCode: '',
  supplierName: '',
  storagePersonnel: '',
  documentDate: formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss'),
  orderStatus:'5',
  invoiceDate: '',
  purOrderNumber: '',
  invoiceNumber: '',
  transferType: '',
  reagentList: []
});

let taskFormRule = {
  tarStoreCode: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  storagePersonnel: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  supplierCode: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  transferType: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ]
};
let reagentForm = reactive({
  orderInfoId: '',
  reaNo: '',
  reaNa: '',
  specModel: '',
  expirDay: '',
  proUnit: '',
  amount: '',
  costPrice: '',
  costs: 0,
  barcode: '',
  vendorNo: '',
  miniUnit: '',
  maxTemp: '',
  minTemp: '',
  stockCondition: '',
  batchNum:''
});

onMounted(() => {
  getJygzzList();
  getLzList();
  taskForm.id = proxy.$route.query.id ? proxy.$route.query.id.toString() : '';
  taskForm.transferType = proxy.$route.query.transferType ? proxy.$route.query.transferType.toString() : '';
  backUrl = proxy.$route.query.url.toString();
  if (taskForm.id) {
    getPatrolTaskById();
  }
});
/**下拉选中行事件 */
async function SelectRowClick(e) {
  e.aimKeys.forEach((r) => {
    taskForm[r.aimKey] = e.row[r.rowKey];
  });
}
/**下拉选中行事件 */
async function SelectRowClick1(e) {
  e.aimKeys.forEach((r) => {
    reagentForm[r.formKey] = e.row[r.rowKey];
  });
  proxy.$refs[`form${1}`].focus();

}
//获取检测方式数据字典
function getJygzzList() {
  jygzzList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'JYGZZ' } })
    .then((res: any) => {
      Object.assign(jygzzList, res.data);
    })
    .catch((err: any) => {});
}
//获取流转集合
function getLzList() {
  lzList.length = 0;
  const url = '/inv/transfer/type/findInvTransferTypeList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      Object.assign(lzList, res.data);
    })
    .catch((err: any) => {});
}

/**下拉选中 */
function dropPullDownConfirm(e) {
  e.aimKeys.forEach((m) => {
    taskForm[m.aimKey] = e.row[m.rowKey];
  });
}

//获取修改所有页面信息
function getPatrolTaskById() {
  const url = '/inv/orderInfo/findOrderInfoAndReagent';
  proxy.$http
    .get(url, { params: { orderInfoId: taskForm.id } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        Object.assign(taskForm, res.data);
      }
    })
    .catch((err) => {
      proxy.$alert(err, '提示');
    });
}

function saveForm(formName: any) {  
  let $el = proxy.$refs[formName];
  
  //判断taskForm的reagentList是否为空
  if (taskForm.reagentList.length === 0) {
    VxeMessage('请选择商品', VxeNotifyType.warning);
    return;
  }else{
    //过滤出reagentList的amount为0的数据
    const filterList = taskForm.reagentList.filter((item) => item.amount === 0);
    if (filterList.length > 0) {
      VxeMessage('商品数量不能为0', VxeNotifyType.warning);
      return;
    }
  }

  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    submiting.value = true;
    let url = '';
    if (taskForm.id) {
      url = '/inv/orderInfo/editOrderInfo';
    } else {
      url = '/inv/orderInfo/addOrderInfo';
    }
    proxy.$http
      .post(url, taskForm)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('提交成功', VxeNotifyType.success);
          taskForm.id = res.data.id;
          //getPatrolTaskById();
          goBack();
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
        submiting.value = false;
      })
      .catch((err) => {
        submiting.value = false;
      });
  });
}
function goBack(): void {
  if (backUrl) {
    proxy.$router.push(backUrl);
  } else {
    proxy.$router.go(-1); //返回上一层
  }
  proxy.$emit('closeDrawer');
}
function showAddReagent() {
  checkReagentShow.value = true;
  proxy.$nextTick(() => {
    sltReagentRef.value?.setPatrolTaskEqList(taskForm.reagentList);
  })
}
function closeReagentDialog() {
  checkReagentShow.value = false;
}
function confirmReagent() {
  const sltEquipmentList = sltReagentRef.value.checkedRowList;
  console.log('sltEquipmentList',sltEquipmentList)
  const patrolTaskEqList = [];
  for (const item of sltEquipmentList) {
    const sm = taskForm.reagentList.some((p: any) => p.reaNo === item.reaNo);
    if (sm) {
      patrolTaskEqList.push(taskForm.reagentList.find((p: any) => p.reaNo === item.reaNo));
    } else {
      const patrolTaskEq = {
        id: '',
        orderInfoId: taskForm.id,
        reaNo: item.reaNo,
        reaNa: item.reaNa,
        specModel: item.specModel,
        expirDay: item.expirDay,
        proUnit: item.proUnit,
        amount: 0,
        costPrice: IsEmpty(item.costPrice) ? 0 : item.costPrice,
        costs: 0,
        barcode: item.barcode,
        vendorNo: item.vendorNo,
        miniUnit: item.miniUnit,
        maxTemp: item.maxTemp,
        minTemp: item.minTemp,
        stockCondition: item.stockCondition
      };
      patrolTaskEqList.push(patrolTaskEq);
    }
  }
  taskForm.reagentList = patrolTaskEqList;
  if (taskForm.reagentList && taskForm.reagentList.length > 0) {
    reagentTableRef.value.setCurrentRow(taskForm.reagentList[0]);
  }
  checkReagentShow.value = false;
}
//回车事件
function keyupEnter(e: any, index: any) {
  if (e.key == 'Enter') {
    if (index == 4) {
      //保存到集合里面
      const patrolTaskEq = {
        orderInfoId: taskForm.id,
        reaNo: reagentForm.reaNo,
        reaNa: reagentForm.reaNa,
        specModel: reagentForm.specModel,
        expirDay: reagentForm.expirDay,
        proUnit: reagentForm.proUnit,
        amount: reagentForm.amount,
        costPrice: IsEmpty(reagentForm.costPrice) ? 0 : reagentForm.costPrice,
        costs: (reagentForm.amount) * (IsEmpty(reagentForm.costPrice) ? 0 : reagentForm.costPrice),
        barcode: reagentForm.barcode,
        vendorNo: reagentForm.vendorNo,
        miniUnit: reagentForm.miniUnit,
        maxTemp: reagentForm.maxTemp,
        minTemp: reagentForm.minTemp,
        stockCondition: reagentForm.stockCondition,
        batchNum: reagentForm.batchNum
      };
      let isData =true;
      for (const item of taskForm.reagentList) {
        if (item.reaNo == patrolTaskEq.reaNo) {
          isData=false;
        }
      }
      if (isData){
        taskForm.reagentList.push(patrolTaskEq);
      }
      resetForm();
      proxy.$refs[`form0`].focus();
    } else {
      proxy.$refs[`form${index + 1}`].focus();
    }
  }
}
function resetForm() {
      reagentForm.orderInfoId= taskForm.id;
      reagentForm.reaNo= '';
      reagentForm.reaNa= '';
      reagentForm.specModel= '';
      reagentForm.expirDay= '';
      reagentForm.proUnit= '';
      reagentForm.amount= '';
      reagentForm.costPrice= '';
      reagentForm.costs= 0;
      reagentForm.barcode= '';
      reagentForm.vendorNo= '';
      reagentForm.miniUnit= '';
      reagentForm.maxTemp= '';
      reagentForm.minTemp= '';
      reagentForm.batchNum= '';
}

function getCosts(row :any){
  row.costs=(row.amount) * (IsEmpty(row.costPrice) ? 0 : row.costPrice);
}
</script>
<style lang="scss" scoped>
#patrolTaskEdit {
  height: 100%;

  .bodyContent {
    height: calc(100% - 90px);

    .el-form {
      margin-top: 10px;
    }

    .contentDiv {
      background-color: $base-white;
      height: calc(100% - 95px);
      margin-top: 10px;

      .el-container {
        .mb10 {
          margin-bottom: 10px;
        }

        .add-btn {
          padding: 5px;
          margin-left: 10px;
        }

        .el-aside {
          background-color: $base-white !important;
          margin: 0;
          padding: 0 10px;
        }

        .el-main {
          background-color: $base-white;

          padding: 0 10px;

          .el-checkbox-group .check-row-inline {
            height: 10px;
            line-height: 30px;
            padding: 0 5px 0 0;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            display: inline-block;

            .el-checkbox {
              width: 70px !important;
              margin-bottom: 2px;
            }

            .inst-checkboxClazz {
              width: auto !important;
              margin-bottom: 2px;
            }

            .el-checkbox__label {
              padding-left: 5px;
            }
          }

          .el-radio-group .check-row-inline {
            height: 10px;
            line-height: 30px;
            padding: 0 5px 0 0;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            display: inline-block;

            .el-radio {
              width: 70px !important;
              margin-bottom: 2px;
            }

            .inst-checkboxClazz {
              width: auto !important;
              margin-bottom: 2px;
            }

            .el-radio__label {
              padding-left: 5px;
            }
          }
        }
      }

      .footerBtn {
        height: 32px;
        background-color: $base-white;
      }
    }
  }
}

:deep(.el-dialog) {
  padding: 0;

  .el-dialog__header {
    padding: 15px;
  }

  .el-dialog__body {
    padding: 0;

    .dialog-footer {
      margin: 10px;
      height: 32px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
